﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace OmniBean_Game_Studio_1._0_Refresh
{
    public partial class OmniBean : Form
    {
        enum FileType { javascript, html, unknown }
        FileType fileType;
        string fileName;


        public OmniBean()
        {
            InitializeComponent();

        }
        private void OpenFile(object sender, EventArgs e)
        {
            string docsDir = Environment.SpecialFolder.MyDocuments.ToString();
            try
            {
                Directory.CreateDirectory(docsDir + "/OmniBean Game Studio/");
            }
            catch { }

            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = docsDir + "/OmniBean Game Studio/";
            openFileDialog1.Filter = "JavaScript Files (*.js)|*.js|HTML Files (*.html)|*.html|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 3;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            fileName = openFileDialog1.FileName;
                            fileNameLabel.Text = fileName;
                            string renderedFN = fileName;
                            string contDir = Path.GetDirectoryName(renderedFN);
                            string procEx = contDir + "processing.js";
                            string processing = "C://Users/" + Environment.UserName + "/AppData/Roaming/Programs/OmniBean/processing.js";
                            string dwnldProcessing = "http://googledrive.com/host/0B9uYmJbyDf52WkJFOWZycEFsT3M/processing.js";
                            if (!File.Exists(processing))
                            {
                                WebClient webClient = new WebClient();
                                try
                                {
                                    Directory.CreateDirectory("C://Users/" + Environment.UserName + "/AppData/Roaming/Programs/OmniBean/");
                                }
                                catch { }
                                webClient.DownloadFile(dwnldProcessing, processing);

                            }
                            if (!File.Exists(procEx))
                            {
                                File.Copy(processing, procEx);
                            }
                            // Insert code to read the stream here.
                            using (StreamReader sr = new StreamReader(myStream))
                            {
                                fileType = FileType.unknown;
                                if (openFileDialog1.FileName.ToString().EndsWith(".html"))
                                {
                                    fileType = FileType.html;
                                }
                                if (openFileDialog1.FileName.ToString().EndsWith(".js"))
                                {
                                    fileType = FileType.javascript;
                                }
                                string content = sr.ReadToEnd();
                                TextEditor.Text = content;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void SaveFile(object sender, EventArgs e)
        {
            Stream myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "JavaScript files (*.js)|*.js|HTML files (*.html)|*.html|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 3;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {

                    fileName = saveFileDialog1.FileName;
                    fileNameLabel.Text = fileName;
                    // Code to write the stream goes here.
                    using (StreamWriter sw = new StreamWriter(myStream))
                    {
                        fileType = FileType.unknown;
                        if (saveFileDialog1.FileName.ToString().EndsWith(".html"))
                        {
                            fileType = FileType.html;
                        }
                        if (saveFileDialog1.FileName.ToString().EndsWith(".js"))
                        {
                            fileType = FileType.javascript;
                            string renderedFN = fileName + ".obgs.html";
                            string contDir = Path.GetDirectoryName(renderedFN);
                            string procEx = contDir + "processing.js";
                            string processing = "C://Users/" + Environment.UserName + "/AppData/Roaming/Programs/OmniBean/processing.js";
                            string dwnldProcessing = "http://googledrive.com/host/0B9uYmJbyDf52WkJFOWZycEFsT3M/processing.js";
                            if (!File.Exists(processing))
                            {
                                WebClient webClient = new WebClient();
                                webClient.DownloadFile(dwnldProcessing, processing);

                            }
                            if (!File.Exists(procEx))
                            {
                                File.Copy(processing, procEx);
                            }
                            if (!File.Exists(renderedFN))
                            {
                                File.WriteAllText(renderedFN, @"
<!DOCTYPE html>
<html>
<body>
<div class=““row”“ style=““text-align: center;”“>
		<script src=““processing.js”“></script>
          <p><canvas width=““400”“ height=““400”“ data-processing-sources=““squareplanet.js”“></canvas>	</p>
        </div>
</body>
</html>

"

                                );
                            }
                        }
                        string content = TextEditor.Text;
                        sw.Write(content);
                    }
                    myStream.Close();

                }
            }
        }

        private void OmniBean_Load(object sender, EventArgs e)
        {

        }

        private void renderPage(object sender, EventArgs e)
        {

            //MessageBox.Show("Rendering HTML");
            try
            {
                //Render HTML
                string renderedFN = fileName;
                if (fileType == FileType.javascript)
                {
                    renderedFN = fileName + ".obgs.html";
                }
                if (fileType == FileType.html)
                {
                    renderedFN = fileName;
                }


                webbrowser1.Navigate(renderedFN);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An Error Occurred: " + ex);
            }

        }

        private void TexerKP(object sender, PreviewKeyDownEventArgs e)
        {

            {
                if (e.Control && e.KeyCode == Keys.S)       // Ctrl-S Save
                {
                    // do what you want here
                    SaveOpenFile();
                    //e.SuppressKeyPress = true;  // stops bing! also sets handeled which stop event bubbling
                }
            }
        }

        private void SaveOpenFile()
        {
            if (fileName != "")
            {
                string content = TextEditor.Text;
                File.WriteAllText(fileName, content);
            }
        }

        private void ExportAsHtml()
        {
            if (fileName != "")
            {
                FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                try
                {
                    // Show the FolderBrowserDialog.
                    string folderName = "";
                    DialogResult result = folderBrowserDialog1.ShowDialog();

                    if (result == DialogResult.OK)
                    {
                        folderName = folderBrowserDialog1.SelectedPath;
                        string value = "Document 1";
                        if (InputBox("Export Project", "Export Project Name:", ref value) == DialogResult.OK)
                        {
                            string exportName = value;
                            string exportDir = folderName + "/" + exportName + "/";
                            try
                            {
                                Directory.CreateDirectory(exportDir);
                            }
                            catch { }
                            string renderedFN = fileName;
                            string contDir = Path.GetDirectoryName(renderedFN);
                            string procEx = contDir + "processing.js";
                            string fileResourceName = fileName.Substring(contDir.Length);
                            MessageBox.Show("Exported Project "+exportName);
                            try
                            {
                                if (!File.Exists(exportDir + "processing.js"))
                                {
                                    File.Copy(procEx, exportDir + "processing.js");
                                }
                                if (!File.Exists(exportDir + fileResourceName))
                                {
                                    File.Copy(fileName, exportDir + fileResourceName);
                                }
                            }
                            catch { }
                            try
                            {
                                if (!File.Exists(exportDir + fileResourceName+".obgs.html"))
                                {
                                    File.Copy(fileName, exportDir + fileResourceName + ".obgs.html");
                                }
                            }
                            catch
                            { }
                            try
                            {
                                if (!File.Exists(exportDir + fileResourceName + ".js"))
                                {
                                    File.Copy(fileName, exportDir + fileResourceName + ".js");
                                }
                            }
                            catch
                            { }
                        }
                    }
                }
                catch { }
            }
        }

        private void LaunchInBrowser(object sender, EventArgs e)
        {
            //MessageBox.Show("Launching in Browser");
            if (fileName != "")
            {
                try
                {
                    if (fileType == FileType.html)
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                    if (fileType == FileType.html)
                    {
                        System.Diagnostics.Process.Start(fileName + ".obgs.html");
                    }
                }
                catch (Exception)// ex)
                {
                    //MessageBox.Show("An Error Occurred Opening in Browser: "+ex.ToString());
                }
            }

        }


        public static DialogResult InputBox(string title, string promptText, ref string value)
        {
            Form form = new Form();
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            Button buttonCancel = new Button();

            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;

            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }

        private void TextEditor_TextChanged(object sender, EventArgs e)
        {

        }

        private void NewFile(object sender, EventArgs e)
        {
            CloseFile();
        }
        private void CloseFile()
        {
            SaveOpenFile();
            TextEditor.Text = "";
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void exportAsHTMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportAsHtml();
        }










    }
}
